<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Log;

define("TOKEN", "sub-device");

class WechatController
{
    public function index()
    {

        $this->valid();
    }


    //验证消息
    public function valid()
    {
        if (isset($_GET['echostr'])) {
            $echoStr = $_GET["echostr"];
            if($this->checkSignature()){
                echo $echoStr;
                exit;
            }
        } else {
            $this->responseMsg();
        }


    }

    //检查签名
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }

    private function responseMsg()
    {
        $postArr = file_get_contents("php://input");
        Log::info($postArr);
        $postObj = simplexml_load_string($postArr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $postObj=json_decode(json_encode($postObj),true);
        $msgType = $postObj['MsgType'];

        switch ($msgType) {
            case 'event':
                $openid = $postObj['FromUserName'];
                $list = $postObj['List'];
                $from = $postObj['ToUserName'];
                $this->subcribe($openid,$list,$from);
                break;
            case 'text':
//                file_put_contents('a.txt',json_encode(['a3'=>$postObj['FromUserName']]));
                break;

            case 'subscribe_msg_popup_event';

                break;
            default:
                // code...
                break;
        }
        // file_put_contents('a.txt',json_encode(['user'=>$postObj->ToUserName,'token'=>$postObj->EventKey]));
        return response()->json(['code'=>0,'msg'=>'success']);
    }

    public function subcribe($openid,$list,$from){
        $user = User::query()->where('openid',$openid)->first();
        if($user){
            foreach($list as $k => $v){
                if($v['TemplateId'] == '6KU5FXZLFqoV3XFZdu0HAF85ZfVYIneU8Nq4N9zMeTM' && $v['SubscribeStatusString'] == 'accept'){
                    $user->sub_1 = 1;
                }else{
                    $user->sub_1 = 0;
                }
                if($v['TemplateId'] == 'DYeA1Z_M4GNeh1uG3VDo1YRablzbg_IUJ0snQeFPdM0' && $v['SubscribeStatusString'] == 'accept'){
                    $user->sub_2 = 1;
                }else{
                    $user->sub_2 = 0;
                }
         }
            $user->save();
        }
    }


    private function qrCodeLogin($openid,$token,$from)
    {

    }
}
